package com.huluobo.user.pages

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.UIState
import com.huluobo.lib_http.Const
import com.huluobo.user.UserIntent
import com.huluobo.user.UserViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.temporal.ChronoUnit

/**
 *  Created by LC on 2025/6/4.
 */
//声明开始时间的日期
lateinit var start: LocalDate

//结束时间的日期
lateinit var end: LocalDate

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddApprovePage(navHostController: NavHostController, vm: UserViewModel = hiltViewModel()) {
    val mmkv = MMKV.defaultMMKV()

    var name by remember {
        mutableStateOf(mmkv.decodeString(Const.PARAM_USERNAME, "未登录").toString())
    }

    var role by remember {
        mutableStateOf(mmkv.decodeString(Const.PARAM_ROLE, "员工").toString())
    }

    //请假 加班 调休
    var type by remember {
        mutableStateOf("请假")
    }

    //控制请假开始时间弹窗
    var isStartTimeShow by remember {
        mutableStateOf(false)
    }

    //控制请假结束时间弹窗
    var isEndTimeShow by remember {
        mutableStateOf(false)
    }

    //请假开始时间
    var startTime by remember {
        mutableStateOf(SimpleDateFormat("yyyy-MM-dd 09:00:00").format(System.currentTimeMillis()))
    }

    //请假结束时间
    var endTime by remember {
        mutableStateOf(SimpleDateFormat("yyyy-MM-dd 18:00:00").format(System.currentTimeMillis()))
    }

    //请假原因
    var reason by remember {
        mutableStateOf("")
    }

    //请假天数
    var hours by remember {
        mutableStateOf("")
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        isShowProgress = false
                        ToastUtils.showLong("添加请假信息失败:${it.msg}")
                        Log.e("TagA", "添加请假信息失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        ToastUtils.showLong("添加请假成功")
                        navHostController.popBackStack()
                    }
                }
            }
        }
    })

    Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(20.dp)) {
        BaseTitle(title = "请假申请", navHostController = navHostController)
        Card(
            border = BorderStroke(1.dp, Color.LightGray), modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = Color.White
            )
        ) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(20.dp)
            ) {
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(20.dp))
                Column(Modifier.height(80.dp), verticalArrangement = Arrangement.SpaceAround) {
                    Text(text = name)
                    Text(text = role)
                }
            }
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假类型 : ")
            RadioButton(selected = type == "请假", onClick = {
                type = "请假"
            })
            Text(text = "请假")
            RadioButton(selected = type == "加班", onClick = {
                type = "加班"
            })
            Text(text = "加班")
            RadioButton(selected = type == "调休", onClick = {
                type = "调休"
            })
            Text(text = "调休")
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "开始时间 : ")
            OutlinedTextField(value = startTime, onValueChange = {}, readOnly = true, trailingIcon = {
                Icon(imageVector = Icons.Default.DateRange, contentDescription = "", Modifier.clickable {
                    isStartTimeShow = true
                })
            })
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "结束时间 : ")
            OutlinedTextField(value = endTime, onValueChange = {}, readOnly = true, trailingIcon = {
                Icon(imageVector = Icons.Default.DateRange, contentDescription = "", Modifier.clickable {
                    isEndTimeShow = true
                })
            })
        }

        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假时长 : ")
            OutlinedTextField(value = hours, onValueChange = {}, readOnly = true, trailingIcon = {
                Text(text = "天")
            })
        }

        var isError by remember {
            mutableStateOf(false)
        }
        Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假原因 : ")
            OutlinedTextField(value = reason, onValueChange = {
                if (it.length > 20) {
                    isError = true
                } else {
                    isError = false
                    reason = it
                }
            }, trailingIcon = {
                Text(text = "${reason.length}/20", fontSize = 11.sp)
            }, isError = isError)
        }

        Button(modifier = Modifier.fillMaxWidth(), onClick = {
            if (TextUtils.isEmpty(hours) || TextUtils.isEmpty(reason)) {
                ToastUtils.showLong("输入项不能为空")
                return@Button
            }

            val map = mapOf(
                Const.PARAM_TYPE to type,
                Const.PARAM_START_TIME to startTime,
                Const.PARAM_END_TIME to endTime,
                Const.PARAM_HOURS to hours,
                Const.PARAM_REASON to reason
            )
            vm.sendIntent(UserIntent.AddApprove(map))
        }) {
            Text(text = "提交")
        }
    }

    //日期选择器的状态
    val state = rememberDatePickerState()
    if (isStartTimeShow || isEndTimeShow) {
        DatePickerDialog(onDismissRequest = {
            isStartTimeShow = false
            isEndTimeShow = false
        }, confirmButton = {
            Text(text = "OK", modifier = Modifier
                .padding(end = 20.dp, bottom = 20.dp)
                .clickable {
                    //格式化日期选择器选中的时间
                    val time = SimpleDateFormat("yyyy-MM-dd").format(state.selectedDateMillis)
                    if (isStartTimeShow) {
                        startTime = "$time 09:00:00"
                        start = LocalDate.parse(SimpleDateFormat("yyyy-MM-dd").format(state.selectedDateMillis))
                        isStartTimeShow = false
                    } else {
                        endTime = "$time 18:00:00"
                        end = LocalDate.parse(SimpleDateFormat("yyyy-MM-dd").format(state.selectedDateMillis))
                        //计算两个时间的间隔
                        hours = ChronoUnit.DAYS
                            .between(start, end)
                            .toString()
                        isEndTimeShow = false
                    }
                })
        }) {
            //日期选择器
            DatePicker(state = state)
        }
    }
}